package cn.com.lsy.product.lepao.service.impl;

import cn.com.lsy.product.lepao.common.Constant;
import cn.com.lsy.product.lepao.model.dao.LpSessionTblMapper;
import cn.com.lsy.product.lepao.model.entities.LpSessionTbl;
import cn.com.lsy.product.lepao.model.entities.LpSessionTblExample;
import cn.com.lsy.product.lepao.service.ISessionService;
import cn.com.lsy.product.lepao.util.CommonFunctionUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.List;

@Service
public class SessionService implements ISessionService {

    @Autowired
    LpSessionTblMapper lpSessionTblMapper;

    @Override
    public List<LpSessionTbl> selectInfoByToken(String token, String roleType) {

        LpSessionTblExample example = new LpSessionTblExample();
        example.createCriteria().andTokenEqualTo(token).andRTypeEqualTo(roleType);

        return lpSessionTblMapper.selectByExample(example);
    }

    @Override
    public boolean createSession(int roleId, String roleType, String token) {

        //清除已存在的token
        LpSessionTblExample example = new LpSessionTblExample();
        example.createCriteria().andRIdEqualTo(roleId).andRTypeEqualTo(roleType);
        lpSessionTblMapper.deleteByExample(example);

        LpSessionTbl lpSessionTbl = new LpSessionTbl();
        try {
            lpSessionTbl.setCreateTime(CommonFunctionUtil.getDateTime(Constant.formatType.second));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        lpSessionTbl.setrId(roleId);
        lpSessionTbl.setrType(roleType);
        lpSessionTbl.setStatus(Constant.status.enable);
        lpSessionTbl.setToken(token);

        if (lpSessionTblMapper.insertSelective(lpSessionTbl) > 0) {

            return true;

        } else {

            return false;
        }

    }

    @Override
    public List<LpSessionTbl> selectInfoByUserId(int userId, String roleType) {

        LpSessionTblExample example = new LpSessionTblExample();
        example.createCriteria().andRIdEqualTo(userId).andRTypeEqualTo(roleType);

        return lpSessionTblMapper.selectByExample(example);
    }
}
